package com.ftdc.app.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(1);

        // 创建一个 Callable 任务
        Callable<Integer> task = () -> {
            Thread.sleep(2000); // 模拟长时间计算
            return 42; // 计算结果
        };

        // 提交任务并获得 Future 对象
        Future<Integer> future = executor.submit(task);

        try {
            // 获取计算结果，阻塞直到结果可用
            Integer result = future.get();
            System.out.println("Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown(); // 关闭线程池
        }
    }
}